<?php

include_once dirname(__FILE__) . '/../system/settings.php';
if ($_POST) {
    $id = $_POST['id'];
    $entitytype = $_POST['entitytype'];
    $name = $_POST['name'];
    $price = str_replace(",", ".", str_replace(".", "", $_POST['price']));
    $description = $_POST['description'];
    $autoquantity = $_POST['autoquantity'];
    $daysamount = $_POST['daysamount'];
    $category_type = $_POST['category'];

    if ($category_type == 'veiculo') {
        $category = 'V';
        if (!empty($id)) {
            if (!PlanosControl::Update($entitytype, $name, $price, $description, $autoquantity, $daysamount, $category, $id)) {
                header("location: " . $_POST['redirect']);
                exit();
            } else {
                PlanosTiposControl::Delete_Tipos($id);
                foreach ($_POST['id_type'] as $id_type) {
                    PlanosTiposControl::Insert($id, $id_type);
                }
            }
        } else {
            if (!$id_insert = PlanosControl::Insert($entitytype, $name, $price, $description, $autoquantity, $daysamount, $category)) {
                header("location: " . $_POST['redirect']);
                exit();
            } else {
                foreach ($_POST['id_type'] as $id_type) {
                    PlanosTiposControl::Insert($id_insert, $id_type);
                }
            }
        }
    } else if ($category_type == 'produtos') {
        $category = 'P';
        if (!empty($id)) {
            PlanosControl::Update($entitytype, $name, $price, $description, $autoquantity, $daysamount, $category, $id);
            header("location: " . $_POST['redirect']);
            exit();
        } else {
            PlanosControl::Insert($entitytype, $name, $price, $description, $autoquantity, $daysamount, $category);
            header("location: " . $_POST['redirect']);
            exit();
        }
    }
    header("location: " . $_POST['redirect']);
} else if ($_GET) {
    $id = $_GET['id'];
    if (!empty($id)) {
        PlanosControl::Delete($id);
        PlanosTiposControl::Delete_Tipos($id);
    }
    header("location: " . $_GET['redirect']);
}
?>
